"""
============================================================================================
Create subdivisions of regions of interest (labels) from the GPS-generated rois or GE data
============================================================================================

Each label is split in  8 subdivisions.
The split labels are saved in subdirectory "labels/labels_8div", in a separate subfolder for each
original label.


"""
# SA & ON 2020-02-28 

import numpy as np
import matplotlib.pyplot as plt

import os
#import os.path as op
import fnmatch
import sys

import mne
#from mne.minimum_norm import apply_inverse_epochs, read_inverse_operator
#from mne import concatenate_epochs

from GE_config import study_dir, gps_dir, subjects_dir, roi_dir
#from UAG_config import uag_svm_dir_old, uag_rule_tag, uag_8divs_tag
from GE_config import block_list, subject_list, subdir_names

print(__doc__)

label_orig_subdir = 'labels_gps'
label_div_subdir = ''

#--------------------------
# Loop over subjects:

#subject = ['GE_06','GE_07', 'GE_08', 'GE_09', 'GE_10', 'GE_11', 'GE_12', 'GE_13', 'GE_14', 'GE_15', 'GE_16', 'GE_17', 'GE_18', 'GE_19', 'GE_20', 'GE_21', 'GE_22', 'GE_23', 'GE_24']

for subject in subject_list:
    print(subject)

    try:

        # Read in the original GPS labels

        label_from = roi_dir + subject
        print(label_from)
        label_names = fnmatch.filter(os.listdir(label_from), '*.label')
        print('Viola!', len(label_names),  'label files found in', label_from)
        
        if len(label_names) == 0 :
            print('No label files found in', label_from)
            continue # No raw files found, move to the next subject


      

        labels_fname_this_subject = [[] for k in range(len(label_names))]
        for index, label in enumerate(label_names):
            labels_fname_this_subject[index] = label_from + '/' + label
        labels = [mne.read_label(label) for label in labels_fname_this_subject]

	
       

        # Create a subdirectory to save the new divided label files:

        label_subdir = study_dir + '/' + subject + '/' + subdir_names['labels'] + '/' + label_div_subdir
        subdir = label_subdir
        if not os.path.exists(subdir):
            os.mkdir(subdir)
            print("Directory " , subdir ,  " Created ")

 

        # Divide each ROI into 8 parts (divide first into 4 parts, then each of them into 2):

        parts_a, parts_b = 4, 2
        for label in labels:
            print('Splitting', label)
            
            # A for the subj-subdirectory for the each divided ROI:
            nohemi_name = label.name.split('-')
            div_subdir = label_subdir + '/' + nohemi_name[0]
            subdir = div_subdir
            if not os.path.exists(subdir):
                os.mkdir(subdir)
                #print("Directory " , subdir ,  " Created ")

            parts = parts_a
            label_div_a = mne.split_label(label, parts=parts, 
                                         subject=subject, subjects_dir=subjects_dir, 
                                         freesurfer=True)
            print('ERROR CHECK')
            for sub_label in label_div_a:
                parts = parts_b
                label_div_b = mne.split_label(sub_label, parts=parts, 
                                             subject=subject, subjects_dir=subjects_dir, 
                                             freesurfer=True)
                for new_label in label_div_b:
                    fname_div = div_subdir + '/' + new_label.name + '.label'
                    #print(fname_div)
                    new_label.save(fname_div)
        
    except:
        print('================================ Problem with subject :', subject)
        print('Oops!', sys.exc_info()[0],'occured.')
        print( sys.exc_info())
        print('Moving on to next subject..')
        print()
        continue
       






